import * as fs from 'fs';
import * as path from 'path';
import * as axios from 'axios';
export class WsdlCache {
    private cache: { [key: string]: string };
    constructor(private cachePath: string) {
        this.cache = {};
        if(!this.cachePath) {
            this.cachePath = path.join(__dirname, '../.cache')
        }
        if (!fs.existsSync(this.cachePath)) {
            fs.mkdirSync(this.cachePath);
        }
        this._load();
    }
    _load() {
        if (fs.existsSync(this.cachePath)) {
            const indexPath = path.join(this.cachePath, 'index.json');
            if (fs.existsSync(indexPath)) {
                const index = fs.readFileSync(indexPath, 'utf-8');
                const indexObj = JSON.parse(index);
                this.cache = indexObj;
            }
        }
    }

    request(uri:string, callback:(err:any, res:any, body:any)=>void) {
        if (this.cache[uri]) {
            callback(null, null, this.get(uri));
        } else {
            axios.get(uri).then((res) => {
                this.cache[uri] = res.data;
                callback(null, res, res.data);
            })
        }
    }
    _save(content:string, uri:string) {
        const bname = path.basename(uri);
        const fname = path.join(this.cachePath, bname);
        this.cache[uri] = bname;
        fs.writeFileSync(path.join(this.cachePath,"index.json"), JSON.stringify(this.cache,null,2));
        fs.writeFileSync(fname, content, 'utf-8');
    }

    get(uri:string) {
        if (this.cache[uri]) {
            return fs.readFileSync(path.join(this.cachePath, this.cache[uri]), 'utf-8');
        }
        return null;
    }
    set(uri: string, content: string) {
       
        this._save(content, uri);
    }

    has (uri:string) {
        return this.cache[uri] !== undefined;
    }
}

